package com.widget;


import java.util.ArrayList;
import java.util.List;
import android.app.Activity;

import android.app.ProgressDialog;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.*;

public class ListAppsActivity extends Activity {
	TextView tv;
	ArrayList<String> appNames,packageNames;
	ArrayList<Integer> indexSearch=new ArrayList<Integer>();
	List<PackageInfo> pkginfo_list;
	List<ApplicationInfo> appinfo_list;
	String path;
	String IP_ADDR;
	String USERNAME;
	ManageProcess process;
	ListView lv;
	NewQAAdapter adapter;
	public ImageView mMoreIv = null;
	public int mSelectedRow=0;
	String [] appNamesArray;
	AbsoluteLayout ll;
	EditText et;
	ArrayList<String> searchResults=new ArrayList<String>();
	private ListMsgHandler mMsgHandler;
	String tempSearchResults[];
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		process = new ManageProcess();
		process.acquireRoot();

		mMsgHandler = new ListMsgHandler(this);
		Bundle bundle = this.getIntent().getExtras();
		path = bundle.getString("PATH");
		IP_ADDR = bundle.getString("IPADDR");
		USERNAME = bundle.getString("USERNAME");
		et = new EditText(this);
		lv=new ListView(this);
		ll=new AbsoluteLayout(this);

		AbsoluteLayout.LayoutParams  editTextLayout=new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.FILL_PARENT, AbsoluteLayout.LayoutParams.WRAP_CONTENT, 0, 0); 
		AbsoluteLayout.LayoutParams  listViewtLayout=new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT, AbsoluteLayout.LayoutParams.WRAP_CONTENT, 0, 50);

		ll.addView(et,editTextLayout);
		ll.addView(lv,listViewtLayout);

		mMoreIv=new ImageView(this);


		PackageManager  pm = getPackageManager();
		pkginfo_list = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES);
		appinfo_list = pm.getInstalledApplications(0);
		appNamesArray =new String[pkginfo_list.size()];
		for(int i=0;i<pkginfo_list.size();i++){


			appNamesArray[i] = pkginfo_list.get(i).packageName;
			indexSearch.add(i);

		}

		adapter=new NewQAAdapter(this);
		adapter.setData(appNamesArray);
		lv.setAdapter(adapter);
		ActionItem push =new ActionItem();
		push.setTitle("Push");
		ActionItem pull =new ActionItem();
		pull.setTitle("Pull");
		final QuickAction mQuickAction = new QuickAction(this);
		mQuickAction.addActionItem(push);
		mQuickAction.addActionItem(pull);
		mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(int pos)
			{
				String dataDirectory;
				String components[];
				dataDirectory= pkginfo_list.get(mSelectedRow).applicationInfo.dataDir;
				int uid = pkginfo_list.get(mSelectedRow).applicationInfo.uid;
				components = dataDirectory.split("/");
				if (pos == 0)
				{
					final ProgressDialog dialog = ProgressDialog.show(ListAppsActivity.this, "Syncing...", 
							"Please wail while all applications are synchronized. This dialog will " +
									" automatically disappear once the sync is done.", true);
					MSGHandler msg;
					msg = new MSGHandler(ListAppsActivity.this); 
					msg.setDialog(dialog);
					ParseStreaming p = new DataParser();
					p.endMatcher(1, msg);
					process.setParser(p);
					dataDirectory= pkginfo_list.get(mSelectedRow).applicationInfo.dataDir;
					process.executeCmd(path+" -aP --delete --delete-excluded "+dataDirectory+" rsync://"+USERNAME+"@"+IP_ADDR+"/"+USERNAME+"/backup/data/data/");
				} 
				else if (pos == 1)
				{
					final ProgressDialog dialog1 = ProgressDialog.show(ListAppsActivity.this, "Syncing...", 
							"Please wail while all applications are synchronized. This dialog will " +
									" automatically disappear once the sync is done.", true);
					mMsgHandler.setDialog(dialog1);
					mMsgHandler.setDataItems(process, components,uid);
					ParseStreaming p = new DataParser();
					p.endMatcher(1, mMsgHandler);
					process.setParser(p);
					process.executeCmd(path+" -aP --delete --delete-excluded rsync://"+USERNAME+"@"+IP_ADDR+"/"+USERNAME+"/backup/data/data/"+components[components.length-1]+" /data/data/");
				}
			}
		});
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				mSelectedRow = indexSearch.get(position); 
				mQuickAction.show(view);

			}
		});
		et.addTextChangedListener(new TextWatcher() {
			int typedTextLength = 0;
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				String typedText=et.getText().toString();
				typedTextLength=typedText.length();
				typedText=typedText.toUpperCase();
				searchResults.clear();
				indexSearch.clear();
				for(int i=0; i<appNamesArray.length;i++)
				{
					if(typedTextLength<=appNamesArray[i].length())
					{
						String temp=appNamesArray[i].toUpperCase();
						if(temp.contains(typedText))
						{
							indexSearch.add(i);
							searchResults.add(appNamesArray[i]);
						}
					}
				}
				tempSearchResults=new String[searchResults.size()];
				for(int i=0;i<tempSearchResults.length;i++)
				{
					tempSearchResults[i]=searchResults.get(i);
				}
				adapter.setData(tempSearchResults);
				lv.setAdapter(adapter);
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		setContentView(ll);  
	}

	public static void acquireFiles(ManageProcess process,String components[],ListMsgHandler mMsgHandler){
		ListParser p1 = new ListParser();
		p1.endMatcher(1, mMsgHandler);
		mMsgHandler.setListParser(p1);
		process.setParser(p1);
		process.executeCmd("ls -R /data/data/"+components[components.length-1]);
	}
	public static void changePermissions(ManageProcess process,int uid,ArrayList <String> dataFiles,ListMsgHandler mMsgHandler){
		Log.d("PERMISSION CHANGE", "Inside Permission change "+dataFiles.size());
		String fileList="";
		ParseStreaming p = new ChmodParser();
		p.endMatcher(dataFiles.size(), mMsgHandler);
		process.setParser(p);
		for(int i=0;i<dataFiles.size();i++){
			String check = dataFiles.get(i);
			Log.d("CHOWN-1", "Executing CHOWN-2");
			if(!check.contains("#"))
				process.executeCmd("chown "+uid+"."+uid+" "+check);
		}
	}
	public void onClick(View v) {
	}
}